import Taro, { Component } from '@tarojs/taro'
import {View, Picker, Input, Text} from '@tarojs/components'
import { AtMessage, AtTextarea, AtButton } from 'taro-ui'
import qs from 'qs'
import './index.scss'
import {getRealLeaveDay, saveOrUpdateLeave, getResidueDay} from '../service'
import {leaveType, getIndex, bpmTypeEnum} from '../../../constant'
import { connect } from '@tarojs/redux'
import moment from 'moment'
import {setRefresh} from "../../../actions/refresh";

@connect(({ refresh }) => ({
  refresh
}), (dispatch) => ({
  setRefresh (isRefresh) {
    dispatch(setRefresh(isRefresh))
  },
}))
export default class attendance extends Component {

  config = {
    navigationBarTitleText: '请假申请'
  };

  constructor (props) {
    super(props);
    this.state = {
      restDays: 0,
      formData: {}
    }
  }

  componentDidMount () {
    let array = window.location.hash.split('?');
    if (array.length>1){
      let obj = qs.parse(array[1]);
      this.setState({formData: JSON.parse(obj.applyData)})
    }
    // getResidueDay().then(res => {
    //   this.setState({restDays: res});
    // })
  }

  onPickerChange = (e, key) => {
    const { formData } = this.state;
    let obj = {...formData};
    if (key === 'type'){
      obj[key] = leaveType[e.detail.value].value;
    }else {
      obj[key] = e.detail.value;
    }
    let verifyKey = ['type','leaveBeginTime','leaveEndTime'];
    if(key === 'leaveBeginTime') obj.leaveBeginTime = moment(obj.leaveBeginTime,'YYYY-M-DD').format('YYYY-MM-DD');
    if(key === 'leaveEndTime') obj.leaveEndTime = moment(obj.leaveEndTime,'YYYY-M-DD').format('YYYY-MM-DD');
    if (verifyKey.indexOf(key) > -1 && obj.type !== null && obj.leaveBeginTime && obj.leaveEndTime){
      let queryData = {type: obj.type, leaveBeginTime: obj.leaveBeginTime, leaveEndTime: obj.leaveEndTime};
      // getRealLeaveDay(queryData).then(res => {
      //   obj.leaveDay = res;
      //   this.setState({formData: obj})
      // })
      this.setState({formData: obj})
    }else {
      this.setState({formData: obj})
    }
  };

  onSubmit = () => {
    let { formData } = this.state;
    if (formData.type === null){
      Taro.atMessage({message: '请假类型不能为空！', type: 'error'});
      return;
    }else if (!formData.leaveBeginTime){
      Taro.atMessage({message: '请假开始日期不能为空！', type: 'error'});
      return;
    }else if (!formData.leaveEndTime){
      Taro.atMessage({message: '请假结束日期不能为空！', type: 'error'});
      return;
    }else if (!formData.leaveDay){
      Taro.atMessage({message: '请假天数不能为空！', type: 'error'});
      return;
    }else if (!formData.leaveRemark){
      Taro.atMessage({message: '请假原因不能为空！', type: 'error'});
      return;
    }
    formData.fileUrl = '';
    formData.createType = 1;
    saveOrUpdateLeave(formData).then(res => {
      if (res.flag){
        Taro.atMessage({message: '保存请假申请成功！', type: 'success',});
        this.props.setRefresh(true);
        this.onReset();
        Taro.navigateBack()
      }
    })
  };

  onReset = () => {
    let {formData} = this.state;
    let resetData = {leaveRemark: '', leaveDay: null, leaveEndTime: null, leaveBeginTime: null, type: null};
    let resetFormData = {...formData, ...resetData};
    this.setState({formData: resetFormData})
  }

  onBack = ()=> {
    Taro.navigateBack()
  }

  render () {
    let { formData, restDays } = this.state;
    return (
      <View className='main-m-t'>
        <AtMessage />
        <View className='content-title'>请填写以下信息</View>
        <View className='fromItem'>
          <View className='fromItem-require'>请假类型：</View>
          <Picker mode='selector' className='content-picker' range={leaveType.map(item => item.label)} value={getIndex(leaveType,formData.type)} onChange={(e)=>this.onPickerChange(e,'type')}>
            {
              (formData.type !== undefined && formData.type !== null)
                ? <View className='picker-value'>{leaveType[getIndex(leaveType,formData.type)].label}</View>
                : <View className='picker-placeholder'>请选择请假类型</View>
            }
          </Picker>
        </View>
        {/*<View className='fromItem' style='align-items: center'>*/}
        {/*  可请假天数：*/}
        {/*  <View className='content-picker'>*/}
        {/*    {restDays}天*/}
        {/*  </View>*/}
        {/*</View>*/}
        <View className='fromItem'>
          <View className='fromItem-require'>开始日期：</View>
          <Picker mode='date' className='content-picker'  onChange={(e)=>this.onPickerChange(e,'leaveBeginTime')}>
            {
              formData.leaveBeginTime
                ? <View className='picker-value'>{formData.leaveBeginTime}</View>
                : <View className='picker-placeholder'>请选择</View>
            }
          </Picker>
        </View>

        <View className='fromItem'>
          <View className='fromItem-require'>结束日期：</View>
          <Picker mode='date' className='content-picker' onChange={(e)=>this.onPickerChange(e,'leaveEndTime')}>
            {
              formData.leaveEndTime
                ? <View className='picker-value'>{formData.leaveEndTime}</View>
                : <View className='picker-placeholder'>请选择</View>
            }
          </Picker>
        </View>

        <View className='fromItem' style='align-items: center'>
          <View className='fromItem-require'>请假天数：</View>
          <View className='content-picker'>
            <Input type='number' onInput={(e) => this.onPickerChange(e, 'leaveDay')} value={formData.leaveDay}/>
          </View>
        </View>
        <View className='fromItem' style='padding-bottom: 12pt'>
          <View className='fromItem-require'>请假说明：</View>
          <AtTextarea
            className='content'
            value={formData.leaveRemark}
            onChange={(e)=>this.onPickerChange({detail: {value: e}},'leaveRemark')}
            maxLength={500}
            placeholder='请输入原因'
          />
        </View>

        <View className='btn-view'>
          <AtButton type='secondary' onClick={this.onBack}>返回</AtButton>
          <AtButton type='primary' onClick={this.onSubmit}>保存</AtButton>
        </View>

      </View>
    )
  }
}
